package com.cyz.web.app.tulingxueyuan.reidis;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("redis/index")
public class IndexController {

    private final StringRedisTemplate stringRedisTemplate;

    @RequestMapping("buy")
    public void buy() {
        String lockKey = "buy_lock";
        String clientId = UUID.randomUUID().toString();
        boolean bol = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId, 10, TimeUnit.SECONDS);
        try {
            if (bol) {
                int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock"));
                if (stock > 0) {
                    stock = stock - 1;
                    stringRedisTemplate.opsForValue().set("stock", String.valueOf(stock));
                    log.info("购买商品成功, 当前库存{}", stock);
                } else {
                    log.error("购买商品失败!!!");
                }
            }
        } finally {
            if (stringRedisTemplate.opsForValue().get(lockKey).equals(clientId)) {
                stringRedisTemplate.delete(lockKey);
            }
        }
    }

}
